﻿#include <zemb/Socket.h>
#include <zemb/Tracer.h>
#include <zemb/FileUtil.h>
#include <zemb/StrUtil.h>
#include <zemb/ArgUtil.h>
#include <zemb/DateTime.h>

using namespace zemb;

int main(int argc, char* argv[])
{
	ArgOption option;
	int interval=1000000;
	uint16 port=5555;
	std::string ip = "127.0.0.1";
	std::string localip = "127.0.0.1";
	Tracer::getInstance().setLevel(TRACE_LEVEL_DBG);
	Tracer::getInstance().addSink(std::make_shared<STDSink>()).start();
	
	if (!option.parseArgs(argc,argv))	/* 解析参数 */
	{
		return RC_ERROR;
	}
	if(option.hasOption("h")>=0)
	{
		FilePath filePath(argv[0]);
		TRACE_YELLOW("udp client help:");
		TRACE_YELLOW("%s [-h] [-l localip] [-p port] [-i ip] [-t interval]",CSTR(filePath.baseName()));
		TRACE_YELLOW("        -h  help");
		TRACE_YELLOW("        -l  local ip");
		TRACE_YELLOW("        -p  server port");
		TRACE_YELLOW("        -i  server ip");
		TRACE_YELLOW("        -t  send interval(us)");
		return RC_OK;
	}

	if(option.hasOption("l")>0)
	{
		localip = option.getValue("l")[0];
	}

	if(option.hasOption("i")>0)
	{
		ip = option.getValue("i")[0];
	}
	
	if(option.hasOption("p")>0)
	{
		port = (uint16)std::stoi(option.getValue("p")[0]);
	}
	else
	{
		TRACE_ERR("udp client need server port: [-p port]!");
		return RC_ERROR;
	}

	if(option.hasOption("t")>0)
	{
		interval = std::stoi(option.getValue("t")[0]);
	}
     /* 客户端建立连接 */
	UdpSocket client;
	if(!client.open(localip,port-1))
	{
		TRACE_ERR("cannot open local socket!");
		return RC_ERROR;
	}
	if (!client.setConnection(ip,port))
	{
		TRACE_ERR("cannot connect server: %s:%d",CSTR(ip),port);
		return RC_ERROR;
	}
	TRACE_INFO("start send to server: %s:%d interval:%d",CSTR(ip),port,interval);
	while(1)
	{
		std::string msg="hello";
		Time startTime = Time::fromMono();
		if(client.sendData(CSTR(msg),msg.size() ,1000)<=0)
		{
			TRACE_ERR("send msg to server error!");
		}
		else
		{
			TRACE_INFO("send msg to server ok!");
		}
		char buf[64];
		if (client.recvData(buf, sizeof(buf),-1)>0)
		{
			Time duration = Time::fromMono()-startTime;
			TRACE_INFO("get server ack time: %lld us!",duration.toMicroSec());
		}
		Thread::usleep(interval);
	}
    return 0;
}
